package badgegenerator.dao;

import badgegenerator.dao.exceptions.DAOException;
import badgegenerator.dao.exceptions.MyBatisInitException;
import badgegenerator.dao.mybatis.IUserMapper;
import badgegenerator.dao.mybatis.MyBatisConnector;
import badgegenerator.model.BadgeProject;
import badgegenerator.model.User;
import org.apache.ibatis.session.SqlSession;

public class UserDAO {
    public User getUserById(Integer id) throws DAOException{
        User resultUser = null;
        SqlSession session = null;
        try{
            session = MyBatisConnector.getSession(false);
            IUserMapper mapper = session.getMapper(IUserMapper.class);
            resultUser = mapper.getUserById(id);
        }
        catch(MyBatisInitException ex){
            throw new DAOException(ex);
        }
        finally{
            if(session != null)
                session.close();
        }
        
        return resultUser; 
    }
    
    public User getUserByNickName(String nickname) throws DAOException{
        User resultUser = null;
        SqlSession session = null;
        try{
            session = MyBatisConnector.getSession(false);
            IUserMapper mapper = session.getMapper(IUserMapper.class);
            resultUser = mapper.getUserByNickName(nickname);
        }
        catch(MyBatisInitException ex){
            throw new DAOException(ex);
        }
        finally{
            if(session != null)
                session.close();
        }
        
        return resultUser; 
    }
    
    public void saveOrUpdate(User user) throws DAOException{
        SqlSession session = null;
        try{
            session = MyBatisConnector.getSession(false);
            IUserMapper userMapper = session.getMapper(IUserMapper.class);
            if(user.getId() == null){
                userMapper.insert(user);
            }
            else{
                userMapper.update(user);
            }
            session.commit();
            
            BadgeProjectDAO projDAO = new BadgeProjectDAO();
            for(BadgeProject proj : user.getProjectList()){
                projDAO.saveOrUpdate(proj, session);
            }
            
            for(BadgeProject proj : user.getProjectList()){
                userMapper.updateBadgeProjectUserId(user.getId(), proj.getId());
            }
            session.commit();
        }
        catch(MyBatisInitException ex){
            throw new DAOException(ex);
        }
        finally{
            if(session != null)
                session.close();
        }
    }
}
